<?php

namespace App\Module\Wap\Controllers;

use App\Module\Wap\Validator\AddBankAccountValidator;
use App\Module\Wap\Validator\IndexValidator;
use App\System\Cis\Model\CisBankAccount;
use App\System\Cis\Model\CisUser;
use App\System\Cis\Repositories\CisBankAccountRepository;
use App\System\Cis\Repositories\CisUserRepository;
use App\System\Fina\Repositories\FinaBankInfoRepository;
use App\System\Fina\Repositories\FinaIntegralRegRecordRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;

/**
 * Class IndexController 主页
 * @package App\Module\Admin\Controllers
 */
class IndexController extends Controller
{
    /**
     * 主页
     */

    //登录
    public function login()
    {
        return view('wap.index.login');
    }
    //登录
    public function alert()
    {
        return view('wap.index.alert');
    }
    //列表页
    public function index()
    {
        $user_id = Session::get('userid');
        $user = CisUserRepository::getInstance();
        $data = $user->getChkList($user_id,true);
        $isEmpty = $data->isEmpty();
        foreach ($data as $k=>$v){
            $refer = $user->getRecommendList($v->id,true);
            $data[$k]['referee_num'] = $refer->count();
        }
        return view('wap.index.index',compact('data','isEmpty'));
    }

    //创客帐号详情
    public function detail(Request $request)
    {
        if($request->isMethod('post')){
            $thepost = $request->only('id','nickName');
            $res = CisUser::where('id',$thepost['id'])->update(['name'=>$thepost['nickName']]);
            if($res){
                return response()->json(['message' => '', 'status' => 'SUCCESS', 'url' => '']);
            }else{
                return response()->json(['message' => '操作失败', 'status' => 'FAIL', 'url' => '']);
            }
        }
        $id = $request['id'];
        $user = CisUserRepository::getInstance();
        $data = $user->getUser($id);
        $referee_num = CisUser::where('referee_id',$id)->count();
        if($data->status!=1){
            return redirect()->route('wap.index.index');
        }
        return view('wap.index.detail',compact('data','referee_num'));
    }

    //申请提现
    public function withdraw(Request $request)
    {
        die('系统维护中');
        $id = $request['id'];
        $bankId = $request['bankId']??0;
        $bankInfo = [];
        if($bankId){
            $res = CisBankAccount::with(['bank'])->find($bankId);
            $bankInfo = $res->toArray();
        }
        $user = CisUserRepository::getInstance();
        $data = $user->getUser($id);
        if($data->status!=1){
            return redirect()->route('wap.index.index');
        }
        return view('wap.index.withdraw',compact('data','id','bankInfo'));
    }

    //登录
    public function ajaxLogin(Request $request)
    {
        if($request->isMethod('post')){
            $thepost = $request->only('mobile','password');
            $cisUser = CisUserRepository::getInstance();
            $res = $cisUser->login($thepost['mobile'],$thepost['password']);
            $msg = !empty($res['message']) ? $res['message'] : '登录失败';
            $status = !empty($res['status']) ? $res['status'] : 'FAIL';
            $url = !empty($res['data']) ? url('/wap/index') : '';
            return response()->json(['message' => $msg, 'status' => $status, 'url' => $url]);
        }
    }

    public function ajaxWithdraw(Request $request)
    {
        die('系统维护中');
        if($request->isMethod('post')){
            (new IndexValidator())->check();
            $thepost = $request->only('wx_id','cash','user_id','password');
            $user = CisUserRepository::getInstance();
            $userInfo = $user->getUser($thepost['user_id']);
            if($thepost['cash'] > $userInfo->integral || $thepost['cash'] < 100 || ($thepost['cash']%100)!=0){
                return response()->json(['message' => '超过额度或额度不是100的整数倍', 'status' => 'FAIL', 'url' => '']);
            }
            $password = $thepost['password'];
            $userId = Session::get('userid');
            $masterUserInfo = $user->getUser($userId);
            if(!Hash::check($password,$masterUserInfo->password)){
                return response()->json(['message' => '登录密码错误', 'status' => 'FAIL', 'url' => '']);
            }
            $bankAccount = CisBankAccount::find($thepost['wx_id']);
            $bankAccountArray = ['id'=>$bankAccount->id,'account_name'=>$bankAccount->account_name,'account_branch_name'=>$bankAccount->bank->bank_name.$bankAccount->account_branch_name,'account_code'=>$bankAccount->account_code,'user_id'=>$bankAccount->user_id];
            $accountJson = json_encode($bankAccountArray,JSON_UNESCAPED_UNICODE);
            $data['income'] = 2;
            $data['type'] = 7;
            $data['record_type'] = 1;
            $data['commission'] = $thepost['cash']*0.05;
            $data['cash'] = $thepost['cash']-$data['commission'];
            $data['after_cash'] = $userInfo->integral - $thepost['cash'];
            $data['bank_info'] = $accountJson;
            $data['status'] = 3;
            $data['user_id'] = $thepost['user_id'];
            $res = false;
            if(CisUser::where('id',$thepost['user_id'])->update(['integral'=>$data['after_cash']])){
                $finance = FinaIntegralRegRecordRepository::getInstance();
                $res = $finance->createFina($data);
            }
            if($res){
                $msg = '申请成功';
                $status = 1;
                $url = url('/wap/index/detail/'.$thepost['user_id']);
            }else{
                $msg = '申请失败';
                $status = 'FAIL';
                $url = '';
            }
            return response()->json(['message' => $msg, 'status' => $status, 'url' => $url]);
        }
    }

    //业绩详情
    public function achievement(Request $request){
        $id = $request['id'];
        $user = CisUserRepository::getInstance();
        $data = $user->getUser($id);
        return view('wap.index.achievement',compact('data'));
    }

    //推荐详情
    public function refereeList(Request $request){
        $id = $request['id'];
        $cisUser = CisUserRepository::getInstance();
        $data = $cisUser->getRecommendList($id,true);
        $referee_num = CisUser::where('referee_id',$id)->count();
        $statusArr = [1=>'正常',2=>'停用',3=>'失效'];
        return view('wap.index.refereeList',compact('data','referee_num','statusArr'));
    }

    //转移帐号
    public function transferAccount(Request $request){
        if($request->isMethod('post')){
            $thepost = $request->only('id','mobile','password');
            $cisUser = CisUserRepository::getInstance();
            $res = $cisUser->transferAccount($thepost);
            return response()->json($res);
        }
        $id = $request['id'];
        return view('wap.index.transferAccount',compact('id'));
    }

    //修改密码
    public function changePassword(Request $request){
        if($request->isMethod('post')){
            $thepost = $request->only('mobile','pwd_old','pwd_new','pwd_confirm');
            $cisUser = CisUserRepository::getInstance();
            $res = $cisUser->changePwd($thepost);
            return response()->json($res);
        }
        return view('wap.index.changePassword');
    }

    //银行卡列表
    public function bankAccountList(Request $request){
        $id = $request['id'];
        $userId = Session::get('userid');
        $cisBankAccount = CisBankAccountRepository::getInstance();
        $data = $cisBankAccount->getList($userId);
        return view('wap.index.bankAccountList',compact('data','id'));
    }

    //绑定银行卡
    public function addBankAccount(Request $request){
        if($request->isMethod('post')){
            (new AddBankAccountValidator())->check();
            $thepost = $request->only('accountName','accountBankId','accountCode','accountBranchName','password');
            $data['account_name'] = $thepost['accountName'];
            $data['account_bank_id'] = $thepost['accountBankId'];
            $data['account_code'] = $thepost['accountCode'];
            $data['account_branch_name'] = $thepost['accountBranchName'];
            $password = $thepost['password'];
            $cisBankAccount = CisBankAccountRepository::getInstance();
            $res = $cisBankAccount->bindBank($password,$data);
            if($res['s']==1){
                $msg = '绑定成功';
                $status = 1;
            }else{
                $msg = $res['m'];
                $status = 'FAIL';
            }
            return response()->json(['message' => $msg, 'status' => $status]);
        }
        $id = $request['id'];
        $bank = FinaBankInfoRepository::getInstance();
        $bankList = $bank->bankList();
        return view('wap.index.addBankAccount',compact('bankList','id'));
    }

    // 删除银行卡
    public function delBankAccount(Request $request){
        if($request->isMethod('post')){
            $id = $request['id'];
            $res = CisBankAccount::where('id',$id)->delete();
            if($res){
                $msg = '操作成功';
                $status = 1;
            }else{
                $msg = '操作失败';
                $status = 'FAIL';
            }
            return response()->json(['message' => $msg, 'status' => $status]);
        }
    }

    public function updateMobile(Request $request){
        $code = $request['code'];
        $mycode = 'aiitec_php';
        if(!$code || $code != $mycode){
            echo '无此权限！';die;
        }
        $list = CisUser::with(['parentUser'])->where('parent_id','!=',0)->get();
        $isset = 0;
        foreach ($list as $v){
            if($v->mobile != $v->parentUser['mobile']){
                $isset = 1;
                echo $v->id.'错误号码为'.$v->mobile.'正确应为'.$v->parentUser['mobile'].'<br/>';
                $res = CisUser::where('id',$v->id)->update(['mobile'=>$v->parentUser['mobile']]);
                if($res){
                    echo $v->id.'号码修改成功！'.'<br/>';
                }else{
                    echo $v->id.'号码修改失败！'.'<br/>';
                }
            }
        }
        if(!$isset){
            echo '不存在手机号错误帐号！';
        }
    }

}
